/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package com.isisufes.joinus.appserver;

import java.io.*;
import java.util.*;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class Parser
{
    static private Map<String,String> data;

    static private class MyHandler extends DefaultHandler
    {
        String item = null;

        public void startElement(String namespaceURI, String localName,
                           String qName, Attributes atts)
        {
            if (localName.equals("item")) {
                item = atts.getValue("", "name");
            }
        }

        public void characters(char[] ch, int start, int length)
        {
            data.put(item, new String(ch, start, length));
        }
    }

    static public Map<String,String> parse(String xml)
    {
        data = new HashMap<String,String>();

        try {
            MyHandler mh = new MyHandler();
            XMLReader xr = XMLReaderFactory.createXMLReader();

            xr.setContentHandler(mh);
            xr.parse(new InputSource(new StringReader(xml)));
        } catch (Exception e) { }

        return data;
    }

    static public String encapsulate(String[] fields, String[] values)
    {
        StringBuilder sb = new StringBuilder();

        for (int i=0; i<fields.length; i++) {
            sb.append("<item name=\""+fields[i]+"\">"+values[i]+"</item>\n");
        }

        return sb.toString();
    }
}
